package cn.foolishbird.crow.step;

import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * @author foolish bird
 * @email luohongtu@foolishbird.cn
 */
public class IteratorBatchDispose<E> {

    private final ReadOnlyIterator<E> readOnlyIterator;

    public IteratorBatchDispose(ReadOnlyIterator<E> readOnlyIterator) {
        this.readOnlyIterator = readOnlyIterator;
    }

    /**
     * 分步处理
     *
     * @param consumer 执行器
     */
    public void stepDispose(Consumer<Collection<E>> consumer) {
        if (Objects.isNull(readOnlyIterator)) {
            throw new RuntimeException("步进读取器不能为空");
        }

        Collection<E> collection = readOnlyIterator.read();
        while (CollectionUtils.isNotEmpty(collection)) {
            consumer.accept(collection);
            readOnlyIterator.forward();
            collection = readOnlyIterator.read();
        }
    }

}
